﻿using PMS.Core.Caching;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;

namespace PMS.Data.Entities
{
    /// <summary>
    /// 所有数据库实体类的基类，需要继承使用
    /// 对所有数据库表进行规范，每张表需要有的字段： Id, IsActive, CreatedOnTimeUtc, UpdatedOnTimeUtc
    /// But!!: 如有表不需要用到公用字段，请在Mapping表对其进行过滤
    /// </summary>
    public abstract partial class BaseEntity
    {
        #region General Columns
        /// <summary>
        /// Gets or sets the entity identifier
        /// </summary>
        public int Id { get; set; }
        /// <summary>
        /// 原则上数据采用软删除(既数据不采取Delte删除，而是IsActive = false设置数据)
        /// 读取数据时需要带上查询条件 IsActive = true
        /// </summary>
        public bool IsActive { get; set; }
        public DateTime CreatedOnTimeUtc { get; set; }
        public DateTime UpdatedOnTimeUtc { get; set; }

        #endregion
        /// <summary>
        /// Get key for caching the entity
        /// </summary>
        public string EntityCacheKey => GetEntityCacheKey(GetType(), Id);

        /// <summary>
        /// Get key for caching the entity
        /// </summary>
        /// <param name="entityType">Entity type</param>
        /// <param name="id">Entity id</param>
        /// <returns>Key for caching the entity</returns>
        public static string GetEntityCacheKey(Type entityType, object id)
        {
            return string.Format(CachingDefaultConfigs.PMSEntityCacheKey, entityType.Name.ToLower(), id);
        }

        /// <summary>
        /// Convert Ids string sperated by comma(something like 1,2,5,6)
        /// to int list for db table field
        /// </summary>
        /// <param name="commaStr"></param>
        /// <returns></returns>
        protected IList<int> ConvertFromString(string commaStr)
        {
            var entityIds = new List<int>();
            if (!string.IsNullOrEmpty(commaStr))
            {
                Type proptype = entityIds.GetType();
                if (!TypeDescriptor.GetConverter(proptype).CanConvertFrom(typeof(string)))
                    return entityIds;
                if (!TypeDescriptor.GetConverter(proptype).IsValid(commaStr))
                    return entityIds;
                ((List<int>)TypeDescriptor.GetConverter(proptype).ConvertFromInvariantString(commaStr))
                   .ToList()
                   .ForEach(btnId => entityIds.Add(btnId));
            }
            return entityIds;
        }

        /// <summary>
        /// Convert int array to string separated by comma
        /// </summary>
        /// <param name="idArray"></param>
        /// <returns></returns>
        protected string ConvertFromArray(IEnumerable<int> idArray)
        {
            if (!(idArray?.Any() ?? false)) return string.Empty;
            idArray.ToList().Sort((x, y) => x.CompareTo(y));
            return string.Join(',', idArray.Select(id => id.ToString()).ToArray());
        }

    }
}
